package base.thread_example.example01;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 设计4个线程，其中两个线程每次对j加1，另外两个线程每次对j减1(不考虑顺序问题)
 */
public class MultipleIncAndDec {

    public static void main(String[] args) {
        ResourceNum r = new ResourceNum(0);

        // 创建2个任务协议接口实现
        Inc inc = new Inc(r);
        Dec dec = new Dec(r);

        // 创建4个线程,2个执行加法,2个执行减法
        new Thread(inc,"----------->加法1").start();
        new Thread(dec,"减法1").start();
        new Thread(inc,"----------->加法2").start();
        new Thread(dec,"减法2").start();
    }

}

// 加法任务
class Inc implements Runnable {
    private ResourceNum r;
    public Inc(ResourceNum r){
        this.r = r;
    }

    @Override
    public void run() {
        while (true){
            r.inc();
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

// 减法任务
class Dec implements Runnable {
    private ResourceNum r;
    public Dec(ResourceNum r){
        this.r = r;
    }

    @Override
    public void run() {
        while (true) {
            r.dec();
            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class ResourceNum {
    private final Logger log = LoggerFactory.getLogger(ResourceNum.class);
    private int num;
    public ResourceNum(int num){
        this.num = num;
    }

    public synchronized void inc(){
        num++;
        log.info("{} -> {}", Thread.currentThread().getName(), num);
    }

    public synchronized void dec(){
        num--;
        log.info("{} -> {}", Thread.currentThread().getName(), num);
    }
}

